package com.googlecode.dgwt.client.dojo.util;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.googlecode.dgwt.client.dojo.Dojo;
import com.googlecode.dgwt.client.dojo.core.JsObject;

/**
 * Provides general support to native JavaScript usage.
 * 
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class JsUtil {

    
    public static final native boolean absEquals(Object a, Object b) /*-{
        return a === b;
    }-*/;

    
    public static final native boolean and(Object a, Object b) /*-{
        return !!(a && b);
    }-*/;
    

    public static final native void destroy(Object obj) /*-{
        delete obj;
    }-*/;


    public static final native String escapeString(String txt) /*-{
        return (txt||"").replace(/"/g, "\\\"").replace(/\\/g, "\\\\");
    }-*/;


    public static <T extends Object> T eval(String text) {
        return eval(text, Dojo.getGlobal());
    }


    public static final native <T extends Object> T eval(String text, JsObject aWindow) /*-{
        return (aWindow||$wnd).eval(text);
    }-*/;


    public static final native boolean isNotEmpty(Object a) /*-{
        return !!a;
    }-*/;
    
    
    public static final native boolean isEmpty(Object a) /*-{
        return !a;
    }-*/;


    public static final native <T extends Object> T or(Object a, Object b) /*-{
        return a || b;
    }-*/;


    public static final native <T extends Object> T or(Object a, Object b, Object c) /*-{
        return a || b || c;
    }-*/;


    public static final native float parseInt(String value) /*-{
        return parseInt(value) || 0;
    }-*/;
    
    
    public static final native float parseFloat(String value) /*-{
        return parseFloat(value) || 0.0;
    }-*/;


    public static final Element createDocumentFragment() {
        return createDocumentFragment(Document.get());
    }

    
    public static final native Element createDocumentFragment(Document doc) /*-{
        return (doc || $doc).createDocumentFragment();
    }-*/;


    public static final native boolean isUndefined(Object value) /*-{
        return undefined == value;
    }-*/;
    
    
    public static final native <T> T getProperty(JavaScriptObject obj, String propertyName) /*-{
        return obj[propertyName];
    }-*/;
    

    public static final native void setProperty(JavaScriptObject obj, String propertyName, Object value) /*-{
        obj[propertyName] = value;
    }-*/;
    
}